package org.ysling.litemall.core.weixin.request;

import com.github.binarywang.wxpay.bean.marketing.transfer.PartnerTransferRequest;
import com.github.binarywang.wxpay.bean.marketing.transfer.PartnerTransferResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.v3.util.RsaCryptoUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.crypto.IllegalBlockSizeException;

@Service
public class WxPartnerTransferResult {

    private static final Gson GSON = (new GsonBuilder()).create();

    private final WxPayService payService;

    public WxPartnerTransferResult(WxPayService payService) {
        this.payService = payService;
    }

    public PartnerTransferResult batchTransfer(PartnerTransferRequest request) throws WxPayException {
        request.getTransferDetailList().forEach((p) -> {
            try {
                if (StringUtils.hasText(p.getUserName())){
                    String userName = RsaCryptoUtil.encryptOAEP(p.getUserName(), payService.getConfig().getVerifier().getValidCertificate());
                    p.setUserName(userName);
                }
            } catch (IllegalBlockSizeException var3) {
                throw new RuntimeException("姓名转换异常!", var3);
            }
        });
        String url = String.format("%s/v3/transfer/batches", this.payService.getPayBaseUrl());
        System.out.println(request);
        String response = this.payService.postV3WithWechatpaySerial(url, GSON.toJson(request));
        return GSON.fromJson(response, PartnerTransferResult.class);
    }
}
